package com.ilop.sthome.ui.fragment.device;

import android.annotation.SuppressLint;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;

import com.example.common.base.BasePresentFragment;
import com.example.common.utils.LiveDataBus;
import com.example.common.view.CustomEmptyView;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.event.EventRefreshDevice;
import com.ilop.sthome.data.event.EventSynchronization;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.DeviceForTypeContract;
import com.ilop.sthome.mvp.present.device.DeviceForTypePresenter;
import com.ilop.sthome.ui.activity.config.ProductActivity;
import com.ilop.sthome.ui.adapter.device.ChooseTypeAdapter;
import com.ilop.sthome.ui.adapter.device.DeviceChildAdapter;
import com.ilop.sthome.utils.ConfigureUtil;
import com.ilop.sthome.view.onScrollCallBack;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.FragmentDeviceTypeBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author skygge
 * @date 2019-10-10.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：设备按类型分类页面
 */
public class DeviceForTypeFragment extends BasePresentFragment<DeviceForTypePresenter, FragmentDeviceTypeBinding> implements DeviceForTypeContract.IView {

    private DeviceChildAdapter mAdapter;
    private ChooseTypeAdapter mTypeAdapter;
    private List<String> mDeviceTypeList;
    private int mChooseTypePosition = 0;
    private List<String> mCurrentDeviceType;
    private Stack<View> mStack;
    private GridLayoutManager mManager;
    private CustomEmptyView mEmptyView;
    private View mFootView;

    private static onScrollCallBack mCallBack;
    private boolean isFirstSyn = true;

    public static DeviceForTypeFragment newInstance(onScrollCallBack callBack){
        mCallBack = callBack;
        return new DeviceForTypeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_device_type;
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresenter = new DeviceForTypePresenter(mContext);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mDeviceTypeList = new ArrayList<>();
        mStack = new Stack<>();
    }

    @Override
    protected void initView() {
        super.initView();
        mAdapter = new DeviceChildAdapter(mContext);
        LayoutAnimationController mAnimation = AnimationUtils.loadLayoutAnimation(mContext, R.anim.layout_animation_fall_down);
        mDBind.rlDeviceList.setLayoutAnimation(mAnimation);
        mDBind.rlDeviceList.setLayoutManager(new GridLayoutManager(mContext, 2));
        mDBind.rlDeviceList.setAdapter(mAdapter);
        mManager = new GridLayoutManager(mContext, 4);
        mTypeAdapter = new ChooseTypeAdapter(mContext);
        mDBind.rlTypeList.setLayoutManager(mManager);
        mDBind.rlTypeList.setAdapter(mTypeAdapter);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.findDeviceByType(null);
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.CHOOSE_DEVICE_TYPE, Integer.class).observe(this , integer -> {
            assert integer != null;
            this.mChooseTypePosition = integer;
            mTypeAdapter.setPosition(integer);
            String name = mDeviceTypeList.get(integer);
            mDBind.tvTypeName.setText(name);
            mCurrentDeviceType = integer == 0 ? null : SmartDevice.getTypeList(mContext, name);
            mPresenter.findDeviceByType(mCurrentDeviceType);
            onClickToChooseType();
        });

        LiveDataBus.get().with(CommonId.KEY_EVENT_REFRESH_DEVICE, EventRefreshDevice.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: subDevice " +  event.getDevice_id());
                mPresenter.refreshByPosition(event.getDevice_type());
            }
        });

        LiveDataBus.get().with(CommonId.REFRESH_DEVICE, Integer.class).observe(this, integer -> {
            Log.e(TAG, "initDataBus: refresh device" + integer);
            mPresenter.findDeviceByType(mCurrentDeviceType);
            mPresenter.findAllDeviceType();
            if (integer!=null && integer == 1 && isFirstSyn){
                mPresenter.findAllSubDevice();
                isFirstSyn = false;
            }
            if (integer!=null && integer == 2){
                removeLoadingView();
            }
        });

        LiveDataBus.get().with(CommonId.KEY_EVENT_SYNCHRONIZATION, EventSynchronization.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "onEventMainThread: synchronization" + event.getState());
                if (event.getState() == EventSynchronization.SYN_DEVICE){
                    mPresenter.findAllDeviceType();
                }
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.llDeviceType.setOnClickListener(v -> onClickToChooseType());
        mDBind.rlDeviceTypeBg.setOnClickListener(v -> onClickToChooseType());
        mDBind.rlDeviceTypeBg.setClickable(false);
        mDBind.deviceTypeScroll.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener)
                (v, scrollX, scrollY, oldScrollX, oldScrollY) -> mCallBack.onScrollDeviceType(scrollY == 0));
    }

    private void onClickToChooseType(){
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        mDBind.rlTypeList.measure(width, height);
        int mTypeViewHeight = mDBind.rlTypeList.getMeasuredHeight(); // 获取高度
        mPresenter.showAllDeviceType(mDBind.llDeviceType, mTypeViewHeight);
    }

    @Override
    public void showDeviceList(List<DeviceInfoBean> list) {
        removeLoadingView();
        mAdapter.setList(list);
        String deviceNum = "(" + list.size() + ")";
        mDBind.tvDeviceNum.setText(deviceNum);
    }

    @Override
    public void showDeviceIsEmpty() {
        mDBind.rlDeviceTypeBg.setVisibility(View.GONE);
        mDBind.rlDeviceList.setVisibility(View.GONE);
        if (mEmptyView == null) {
            mEmptyView = new CustomEmptyView(mContext);
            mDBind.frameLayout.addView(mEmptyView);
            mStack.push(mEmptyView);
            mEmptyView.setCallBack(() -> skipAnotherActivity(ProductActivity.class));
        }
    }

    @Override
    public void showDeviceType(List<String> types) {
        this.mDeviceTypeList = types;
        mManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                return ConfigureUtil.gridLayoutLineNum(types.get(i).length());
            }
        });
        mDBind.rlTypeList.setLayoutManager(mManager);
        mTypeAdapter.setTypeList(types);
        mTypeAdapter.setPosition(mChooseTypePosition);
    }

    @Override
    public void showArrowIcon(boolean isOpen) {
        mDBind.ivTypeIcon.setRotation(isOpen ? 180f : 0f);
        mDBind.rlDeviceTypeBg.setBackgroundColor(isOpen ? 0x40000000 : 0x00000000);
        mDBind.rlDeviceTypeBg.setClickable(isOpen);
    }

    @SuppressLint("InflateParams")
    @Override
    public void showLoadingView() {
        if (mFootView == null) {
            mFootView = LayoutInflater.from(mContext).inflate(R.layout.layout_synchro_view, null, false);
            mDBind.footView.addView(mFootView);
            mStack.push(mFootView);
        }
    }

    @Override
    public void removeLoadingView() {
        if (mStack.size()>0){
            if (mEmptyView!=null){
                mDBind.frameLayout.removeView(mEmptyView);
                mDBind.rlDeviceTypeBg.setVisibility(View.VISIBLE);
                mDBind.rlDeviceList.setVisibility(View.VISIBLE);
                mEmptyView = null;
            }
            if (mFootView != null){
                mDBind.footView.removeView(mStack.pop());
                mFootView = null;
            }
        }
    }
}
